package com.hao.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hao.eduservice.entity.EduSubject;
import com.hao.eduservice.entity.excel.SubjectData;
import com.hao.eduservice.service.EduSubjectService;
import com.hao.servicebase.exceptionhandler.GuliException;

/**
 * @author chenwenhao
 * @version 1.0.0
 * @ClassName SubjectExcelListener.java
 * @Description TODO
 * @createTime 2020/11/30,21:09
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    //不能由spring管理，需要自己new，也不能注入其他对象，通过构造函数，注入service对象

    private EduSubjectService subjectService;

    public SubjectExcelListener(){ }

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData == null){
            throw new GuliException(20001,"文件无内容");
        }
        //一级分类
        EduSubject oneSubject = this.oneExist(subjectData.getOneSubjectName());
        if (oneSubject == null){
            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(oneSubject);
        }
        //二级分类
        String pid = oneSubject.getId();
        EduSubject twoSubject = this.twoExist(subjectData.getOneSubjectName(), pid);
        if (twoSubject == null){
            twoSubject = new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(twoSubject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    /**
     * 判断是否已存在一级分类
     *
     * @param name           的名字
     * @return {@link EduSubject}
     */
    private EduSubject oneExist(String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject subject = subjectService.getOne(wrapper);
        return subject;
    }

    /**
     * 判断是否已存在二级分类
     *
     * @param name           的名字
     * @return {@link EduSubject}
     */
    private EduSubject twoExist(String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject subject = subjectService.getOne(wrapper);
        return subject;
    }

}
